'use strict';

const axios = require('axios')
// import urlJoin from 'url-join';
const urlJoin = require('url-join')// 4.0.1
const semver = require('semver')

function getNpmInfo(npmName, registry) {
    // TODO
  if (!npmName) {
    return null
  }
  const registryUrl = registry || grtDefaultRegistry()
  const npmInfoUrl = urlJoin(registryUrl, npmName)
  // console.log('getNpmInfo:  ' + npmInfoUrl)
  return axios.get(npmInfoUrl).then(response => {
    // console.log(response)
    if (response.status === 200) {
      return response.data
    }
    return null
  }).catch(err => {
    return Promise.reject(err)
  })
}

function grtDefaultRegistry(isOriginal = true) {
  return isOriginal ? 'http://registry.npmjs.org' : 'https://registry.npmmirror.com'
}

async function getNpmVersions(npmName, registry) {
  const data = await getNpmInfo(npmName, registry)
  // console.log(data)
  if (data?.versions) {
    return Object.keys(data.versions)
  } else {
    return []
  }
}

// 获取所有满足条件的verions
function getSemverVersions(baseVersions, versions) {
  return versions
  .filter(item => semver.satisfies(item, `^${baseVersions}`))
  .sort((a, b) => semver.gt(b, a))
}

async function getNpmSemverVersions(baseVersions, npmName, registry) {
  const version = await getNpmVersions(npmName, registry)
  const newVersions = getSemverVersions(baseVersions, version)
  return newVersions && newVersions.length > 0 ? newVersions[newVersions.length - 1] : null
}

// 获取最新版本号
async function getNpmLatestVersion(npmName, registry) {
  const version = await getNpmVersions(npmName, registry)
  // console.log(2222, version)
  if (version) {
     return version.sort((a, b) => semver.gt(b, a))[version.length - 1]
  }
  return null
}

module.exports = {
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersions,
  grtDefaultRegistry,
  getNpmLatestVersion
}